﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using QMERP.Domain.Enums;
using QMERP.Infrastructure.EFCore;
using QMERP.Infrastructure.Extensions;

namespace QMERP.Application.Services
{
    public class SerialNumberService : ISerialNumberService
    {
        private readonly QMERPDbContext _db;
        public SerialNumberService(QMERPDbContext db)
        {
            _db = db;
        }
        /// <summary>
        /// 获取对应的SerialNumber并更新
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetSerialNumber(SerialNumberTypeEnum serialNumberType)
        {
            return await GetSerialNumber(serialNumberType.ToString());
        }

        /// <summary>
        /// 获取对应的SerialNumber并更新
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetSerialNumber(string serialNumberType)
        {
            int nowYear = DateTime.Now.Year;
            string nowMonthStr = DateTime.Now.ToString("MM");
            string nowYearStr = DateTime.Now.ToString("yy");

            var model = await _db.SerialNumber.Where(x => x.Type == serialNumberType.ToString()).FirstOrDefaultAsync();
            if (model == null)
            {
                var prefix = serialNumberType.GetDescription<SerialNumberTypeEnum>();
                model = new()
                {
                    Type = serialNumberType,
                    Number = 1,
                    Prefix = prefix,
                    YearNumber = nowYear,
                };
            }
            else
            {
                if (model.YearNumber != nowYear)
                {
                    model.YearNumber = nowYear;
                    model.Number = 1;
                }
            }
            string newNumber = model.Prefix + nowYearStr + nowMonthStr + model.Number.ToString().PadLeft(7, '0');

            model.Number++;

            await _db.SaveChangesAsync();

            return newNumber;
        }
    }
}
